package com.zhouwr.common.core.vo;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhouwr.common.core.util.SqlUtils;
import com.zhouwr.common.core.util.StringUtils;

import java.util.Map;

/**
 * @description: 查询参数
 * @author zhouwr
 * @create: 2020-10-07 21:40
 */
public class Query<T> {

    public IPage<T> getPage(Map<String, Object> params) {
        return this.getPage(params, null, false);
    }

    public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        // 当前页码
        long curPageNo = 1;
        // 页大小
        long pageSize = 10;

        if (params.get("curPageNo") != null) {
            curPageNo = Long.parseLong((String) params.get("curPageNo"));
        }
        if (params.get("pageSize") != null) {
            pageSize = Long.parseLong((String) params.get("pageSize"));
        }

        //分页对象
        Page<T> page = new Page<>(curPageNo, pageSize);

        //分页参数
        params.put("curPageNo", page);

        //排序字段
        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String orderField = SqlUtils.sqlInject((String) params.get("orderField"));
        String orderBy = (String) params.get("orderBy");


        //前端字段排序
        if (StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(orderBy)) {
            if ("asc".equalsIgnoreCase(orderBy)) {
                return page.addOrder(OrderItem.asc(orderField));
            } else {
                return page.addOrder(OrderItem.desc(orderField));
            }
        }

        //没有排序字段，则不排序
        if (StringUtils.isBlank(defaultOrderField)) {
            return page;
        }

        //默认排序
        if (isAsc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        } else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }

        return page;
    }
}
